<?php

namespace App\Providers\Mobile;

use App\Contracts\Mobile\MobileCode as MobileCodeContract;
use App\Contracts\Mobile\MobileMessage;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Log;

/**
 * 发送手机验证码
 * Class MobileCode
 * @package App\Services\Mobile
 */
class MobileCode implements MobileCodeContract {


	private $errMessage = [
		1000 => '发送成功',
		1002 => '手机号码格式不正确',
		1003 => '请不要频繁发送',
	];

	private $message;

	//验证码生存时间
	private $codeExpire = 18000;

	public function __construct(MobileMessage $message) {
		$this->message = $message;
	}


	/**
	 * 发送手机验证码
	 * 每 $timeout 秒发送一次
	 * @param     $mobile
	 * @param int $num
	 * @param int $timeout
	 * @return array
	 */
	public function send($mobile, $num = 6, $timeout = 60) {
		$code = getcode($num, 1);
		if (!preg_match('/[0-9]{11}/', $mobile)) {
			return ['error' => 1002, 'message' => $this->errMessage[1002]];
		}

		//限制频繁发送
		if (Redis::get('string:mobile_code_timeout:' . $mobile)) {
			return ['error' => 1003, 'message' => $this->errMessage[1003]];
		} else {
			Redis::set('string:mobile_code_timeout:' . $mobile, 1);
			Redis::expire('string:mobile_code_timeout:' . $mobile, $timeout);
		}

		//记录验证码
		$this->setCode($mobile, $code);

		 //发送短信
		$message = trans('mobile.mobile_code', ['code' => $code, 'expire' => 30]);
		$res     = $this->message->send($mobile, $message);
		if ($res['error'] != 0) {
			//记录失败信息
			Log::error('短信发送失败: 号码:' . $mobile . ' 错误号码:' . $res['error'] . ' 错误信息:' . $res['msg']);
		}

		return ['error' => 1000, 'message' => $this->errMessage[1000]];
	}

	/**
	 * 获取指定手机的验证码
	 * @param $mobile
	 * @return int
	 */
	public function getCode($mobile) {
		return Redis::get('string:mobile_code:' . $mobile);
	}

	/**
	 * 将验证码记录进redis
	 * @param $mobile
	 * @param $code
	 */
	private function setCode($mobile, $code) {
		Redis::set('string:mobile_code:' . $mobile, $code);
		Redis::expire('string:mobile_code:' . $mobile, $this->codeExpire);
	}

}